package com.woniuxy.gobang84.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.woniuxy.gobang84.entity.User;
import com.woniuxy.gobang84.exception.DAOException;
import com.woniuxy.gobang84.util.DbUtil;

/**
 * 用户DAO
 *
 * @author 老谭 (<a href="http://www.woniuxy.com">蜗牛学苑</a>)
 *
 */
public class UserDAO {
	public void add(User user) {
		String sql = "insert into chess_user(account,password,regtime,score) values(?,?,now(),?)";
		Object[] params = { user.getAccount(), user.getPassword(), user.getScore() };
		DbUtil.execute(sql, params);
	}

	/**
	 * 查询指定的账号是否存在
	 * 
	 * @param account
	 * @return 如果存在，返回true，否则，返回false
	 */
	public boolean isExist(String account) {
		String sql = "select count(*) from chess_user where account=?";
		Connection conn = DbUtil.getConnection();
		PreparedStatement pstmt;
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, account);
			ResultSet rs = pstmt.executeQuery();
			rs.next();
			return rs.getInt(1) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
			// 记日志
			throw new DAOException("执行SQL：" + sql + "出错!", e);
		} finally {
			DbUtil.closeConnection(conn);
		}
	}

	/**
	 * 更新用户积分
	 * 
	 * @param id    用户ID
	 * @param delta
	 */
	public void updateScore(int id, int delta) {
		String sql = "update chess_record set score=score+? where id=?";
		DbUtil.execute(sql, delta, id);
	}

	/**
	 * 更新用户积分
	 * 
	 * @param id    用户ID
	 * @param delta
	 */
	public void updateScore(String account, int delta) {
		String sql = "update chess_user set score=score+? where account=?";
		DbUtil.execute(sql, delta, account);
	}

	public void updatePassword(int id, String password) {

	}

	public User getById(int id) {
		return null;
	}

	public User getByAccountAndPassword(String account, String password) {
		return null;
	}

}
